/* model */
import { ConnectorField, ConnectorModuleComponentNameEnum, ConnectorToField } from '@src/modules/connector/model'
/* scss */
import '@src/modules/connector/components/connector-dialog-detail/column.scss'
/* vue */
// @ts-ignore
import { ComponentInstance, ComponentRenderProxy, defineComponent, PropType, computed, ref, watch, Ref } from 'vue'
import { CommonComponentInstance } from '@model/VC'
import { CreateElement } from 'vue'
/* types */
import Column from '@model/types/Column'
/* util */
import { connectorToFields2FormFields, sortConnectorToFieldsByShowFieldNameList, getSupportedDisplayConnectorColumns } from '@src/modules/connector/util'
import { uuid } from 'pub-bbx-utils'
import { isEmpty } from '@src/util/type'
import { message } from '@src/util/message'
import { t } from '@src/locales'

export type ConnectorModuleConnectorDialogDetailColumnProps = {
  
}

export interface ConnectorModuleConnectorDialogDetailColumnSetupState {
  
}

export enum ConnectorModuleConnectorDialogDetailColumnEmitEventNameEnum {
  Input = 'input',
  Save = 'save',
  Change = 'change',
}

export type ConnectorModuleConnectorDialogDetailColumnInstance = ComponentInstance & ConnectorModuleConnectorDialogDetailColumnSetupState
export type ConnectorModuleConnectorDialogDetailColumnVM = ComponentRenderProxy<ConnectorModuleConnectorDialogDetailColumnProps> & CommonComponentInstance & ConnectorModuleConnectorDialogDetailColumnInstance

// 表格列默认宽度
const TableColumnDefaultWidth = '120px'
const BizSelectColumnRef = 'BizSelectColumnComponent'

export default defineComponent({
  name: ConnectorModuleComponentNameEnum.ConnectorModuleConnectorDialogDetailColumn,
  emits: [
    ConnectorModuleConnectorDialogDetailColumnEmitEventNameEnum.Input,
    ConnectorModuleConnectorDialogDetailColumnEmitEventNameEnum.Save,
    ConnectorModuleConnectorDialogDetailColumnEmitEventNameEnum.Change,
  ],
  props: {
    columns: {
      type: Array as PropType<ConnectorToField[]>,
      default: () => []
    },
    maxLength: {
      type: Number | String,
      default: 0 // 0 不限制选择字段个数
    },
  },
  setup(props: ConnectorModuleConnectorDialogDetailColumnProps, { emit }) {
    
    const tableKey: Ref<string> = ref(uuid())
    
    const tableColumns: Ref<ConnectorField[]> = ref([])
    
    const onValueInputHandler = (value: string[]) => {
      emit(ConnectorModuleConnectorDialogDetailColumnEmitEventNameEnum.Input, value)
    }
    
    return {
      tableColumns,
      tableKey,
      onValueInputHandler
    }
  },
  watch: {
    columns: {
      immediate: true,
      handler(newValue: ConnectorToField[]) {
        const columns = getSupportedDisplayConnectorColumns(newValue)
        this.tableColumns = connectorToFields2FormFields(columns)
      }
    }
  },
  methods: {
    /** 
     * @description 获取发送显示表单字段名称列表
    */
    emitShowFieldNameList(showFieldNameListValue: string[]) {

      if (showFieldNameListValue) {
        this.onValueInputHandler(showFieldNameListValue)
        return
      }
      
      const showFieldNameList = this.tableColumns.filter(item=> item.show).map(column => column.fieldName)
      
      this.onValueInputHandler(showFieldNameList)
      
    },
    emitToFieldList(toFieldList: ConnectorToField[]) {
      this.$emit(ConnectorModuleConnectorDialogDetailColumnEmitEventNameEnum.Change, toFieldList)
    },
    /** 
     * @description 重置表格
    */
    reBuildTableKey() {
      this.tableKey = uuid()
    },
    /** 
     * @description 打开选择列弹窗
    */
    openSelectColumnDialog() {
      
      const bizSelectColumnComponent = (this.$refs[BizSelectColumnRef] || {}) as any
      
      bizSelectColumnComponent.open(this.tableColumns, {})
      
    },
    /** 
     * @description 保存选择列数据
    */
    saveColumnData(event: { data: ConnectorField[] }) {
      
      const tableColumns = event?.data || []

      this.$emit(ConnectorModuleConnectorDialogDetailColumnEmitEventNameEnum.Save, tableColumns)

      const showFieldNameList = tableColumns.filter(item => item.show).map(column => column.fieldName)

      const sortedToFieldList = sortConnectorToFieldsByShowFieldNameList(this.columns, showFieldNameList)

      this.emitToFieldList(sortedToFieldList)
      
      this.reBuildTableKey()
      
      this.$nextTick(() => {
        this.emitShowFieldNameList(showFieldNameList)
      })

    },
    // 给表单设计器提供的获取选择列保存后的字段
    getTableColumns(): ConnectorField[] {
      return this.tableColumns || []
    },
    validateColumn(columns: ConnectorField) {
      
      const isEmptyColumns = isEmpty(columns)
      
      if (isEmptyColumns) {
        message.error(t('common.connector.tips.tip8'))
        return false
      }
      // 如果设置了最多选择多少个字段
      if(this.maxLength && columns.length > this.maxLength) {
        message.error(t('common.connector.maxFieldsLength', {length: this.maxLength}))
        return false
      }
      
      return true
    },
    setTableColumns(columns: ConnectorField) {
      this.tableColumns = columns
    }
  },
  render(h: CreateElement) {
    return (
      <div class={ConnectorModuleComponentNameEnum.ConnectorModuleConnectorDialogDetailColumn}>
        
        <div class="connector-module-connector-dialog-detail-column-header">
          {t('common.connector.title.formShowFields')}
        </div>
        
        <div class="connector-module-connector-dialog-detail-column-footer">
          
          <div class="connector-module-connector-dialog-detail-column-sub-title">
            {t('common.connector.subTitle.title5')}
          </div>
          
          <div 
            class="connector-module-connector-dialog-detail-column-toggle-text" 
            onClick={this.openSelectColumnDialog}
          >
            {t('common.connector.subTitle.title6')}
          </div>
          
        </div>
        
        <div class="connector-module-connector-dialog-detail-column-table">
          <el-table
            border
            header-row-class-name='base-table-header-v3'
            row-class-name='base-table-row-v3'
            stripe
            key={this.tableKey}
          >
            {
              this.tableColumns.filter((column: ConnectorField) => column.show).map((column: ConnectorField) => {
                return (
                  <el-table-column
                    show-over-flow-tooltip
                    label={column.displayName}
                    key={column.fieldName}
                    prop={column.fieldName}
                    minWidth={TableColumnDefaultWidth}
                    resizable={false}
                  >
                  </el-table-column>
                )
              })
              
            }
          </el-table>
        </div>
        
        <biz-select-column 
          class="connector-module-connector-dialog-detail-select-column"
          ref={BizSelectColumnRef} 
          validate={this.validateColumn}
          onSave={this.saveColumnData}
          modalTitle={t('common.connector.showFields')}
          max={this.maxLength}
        />
        
      </div>
    )
  }
})
